package logic

import (
	"context"
	"day15/api/internal/svc"
	"day15/api/internal/types"
	"day15/api/pkg"
	"day15/model/mysql"
	"day15/rpc/user"
	"strconv"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdatePasswordLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordLogic {
	return &UpdatePasswordLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdatePasswordLogic) UpdatePassword(req *types.UserUpdatePasswordRequest) (resp *types.ApiResponse, err error) {
	uid := l.ctx.Value("uid")
	//断言
	uidString, ok := uid.(string)
	if !ok {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "参数错误",
			Data: nil,
		}, nil
	}
	userModel := mysql.User{}
	userId, _ := strconv.Atoi(uidString)
	password, err := userModel.FindPwdById(userId)
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "服务器内部错误",
			Data: nil,
		}, nil
	}
	// 123456
	err = pkg.VerifyPassword(req.OldPassword, password)
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "旧密码输入错误",
			Data: nil,
		}, nil
	}

	saltedPwd, _ := pkg.GenSaltPassword(req.NewPassword)
	_, err = l.svcCtx.UserSrv.UserUpdatePassword(l.ctx, &user.UserUpdatePasswordReq{
		Id:       uidString,
		Password: saltedPwd,
	})
	if err != nil {
		return &types.ApiResponse{
			Code: 0,
			Msg:  "密码修改失败",
			Data: nil,
		}, nil
	}
	return &types.ApiResponse{
		Code: 200,
		Msg:  "密码修改成功",
		Data: nil,
	}, nil
}
